package com.ibm.android;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;

import com.ibm.android.format.BusinessData;

public class HistoryStore {
	public class Transaction {
		public Date mDate;
		public BusinessData mData;
	}

	private static final String sStoreFile = new String("paymenthistory.txt");

	private Context mContext;
	private List<Transaction> mTransactions;

	public HistoryStore(Context context) {
		mContext = context;
		mTransactions = new ArrayList<HistoryStore.Transaction>();
		loadItems();
	}

	public void clear() {
		mTransactions.clear();
		mContext.deleteFile(sStoreFile);
	}

	public boolean contains(BusinessData bd) {
		for (Transaction t : mTransactions) {
			if (t.mData.getIdTransaction().equals(bd.getIdTransaction()))
				return true;
		}

		return false;
	}

	public void addItem(BusinessData bd) {
		Calendar cal = Calendar.getInstance();

		Transaction t = new Transaction();
		t.mDate = cal.getTime();
		t.mData = bd;

		mTransactions.add(0, t); // Prepend it so that we get most recent items
									// first.

		try {
			FileOutputStream stream = mContext.openFileOutput(sStoreFile,
					Context.MODE_APPEND);
			DataOutputStream out = new DataOutputStream(stream);
			out.writeBytes(DateUtil.dateToString(t.mDate) + "\n");
			out.writeBytes(bd.rawText() + "\n---\n");
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public List<Transaction> items() {
		return mTransactions;
	}

	private void loadItems() {
		try {
			FileInputStream stream = mContext.openFileInput(sStoreFile);
			DataInputStream in = new DataInputStream(stream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;
			int pos = 0;
			Transaction t = new Transaction();
			while ((line = br.readLine()) != null) {
				if (line.equals("---")) {
					mTransactions.add(t);
					t = new Transaction();
					pos = 0;
				} else if (pos == 0) {
					t.mDate = DateUtil.dateFromString(line);
					if (t.mDate == null) {
						clear();
						return;
					}
					++pos;
				} else {
					t.mData = new BusinessData(line);
				}
			}
		} catch (FileNotFoundException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			// Should be replaced by a backup, but for now we just remove the
			// file if it fails to parse.
			clear();
			return;
		}
	}
}
